package com.mvcplus.system.controller;

import com.mvcplus.common.constant.GlobalConstant;
import com.mvcplus.common.controller.BaseController;
import com.mvcplus.common.model.SessionInfo;
import com.mvcplus.common.utils.MD5Util;
import com.mvcplus.system.model.SysUser;
import com.mvcplus.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by BINGO on 2016/10/27.
 * 用户登陆跳转
 */
@Controller
@Scope(value = "prototype")
@RequestMapping("main")
public class LoginController extends BaseController {

    private final ISysUserService sysUserService;

    @Autowired
    public LoginController(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @RequestMapping(value = "index")
    public ModelAndView login(HttpServletRequest request) {
        SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO);
        if ((sessionInfo != null) && (sessionInfo.getId() != null)) {
            return new ModelAndView("index");
        }
        return new ModelAndView("login");
    }

    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Object login(SysUser user, HttpSession session) {
        user.setPassword(MD5Util.md5(user.getPassword()));
        SysUser sysuser = sysUserService.selectOne(user);
        if (sysuser != null) {
            if (sysuser.getStatus() == 1) {
                return renderError("该用户已被禁用！");
            } else {
                SessionInfo sessionInfo = new SessionInfo();
                sessionInfo.setId(sysuser.getId());
                sessionInfo.setLoginname(sysuser.getEmail());
                sessionInfo.setName(sysuser.getNickname());
                // user.setIp(IpUtil.getIpAddr(getRequest()));
                sessionInfo.setResourceList(sysUserService.getResourceList(sysuser.getId()));
                sessionInfo.setResourceAllList(sysUserService.getAllResourceList());
                session.setAttribute(GlobalConstant.SESSION_INFO, sessionInfo);
                return renderSuccess("登陆成功！");
            }
        } else {
            return renderError("用户名或密码错误！");
        }
    }

    @ResponseBody
    @RequestMapping("/logout")
    public Object logout(HttpSession session) {
        if (session != null) {
            session.invalidate();
        }
        return renderSuccess("注销成功！");
    }
}
